package com.ding.dailyup.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ding.dailyup.constant.HotIndustryDayTypeEnum;
import com.ding.dailyup.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class HotIndustryService {
	@Autowired
	private RedisService redisService;
	private static Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");

	public void downloadHotIndustry() {
		for (HotIndustryDayTypeEnum hotIndustryDayTypeEnum : HotIndustryDayTypeEnum
				.values()) {
			String queryUrl = hotIndustryDayTypeEnum.getQueryUrl();
			String queryData = HttpRequest.get(queryUrl).execute().body();
			if (StrUtil.isNotEmpty(queryData)) {
				Matcher matcher = pattern.matcher(queryData);
				JSONArray data = new JSONArray();
				if (matcher.find()) {
					data = JSONObject.parseObject(matcher.group())
							.getJSONObject("data").getJSONArray("diff");

				}
				redisService.setHotIndustry(hotIndustryDayTypeEnum.getDayType(),
						data);
			}
		}
	}

	public JSONArray getHotIndustry(int dayType) {
		JSONArray hotIndustry = redisService.getHotIndustry(dayType);
		if (ObjectUtil.isNotNull(hotIndustry)) {
			return hotIndustry;
		}
		// 缓存中没有获取到, 需要查询
		String queryUrl = HotIndustryDayTypeEnum.getQueryUrl(dayType);
		String queryData = HttpRequest.get(queryUrl).execute().body();
		if (StrUtil.isNotEmpty(queryData)) {
			Matcher matcher = pattern.matcher(queryData);
			JSONArray data = new JSONArray();
			if (matcher.find()) {
				data = JSONObject.parseObject(matcher.group())
						.getJSONObject("data").getJSONArray("diff");

			}
			redisService.setHotIndustry(dayType, data);
			return data;
		} else {
			return new JSONArray();
		}
	}

}
